/*
 *  Copyright (C) 2010 Taylor Leese (tleese22@gmail.com)
 *
 *  This file is part of jappstart.
 *
 *  jappstart is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  jappstart is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with jappstart.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.jappstart.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dk.poitalk.controller.ClaimController;
import org.dk.poitalk.controller.DataTablesRequest;
import org.dk.poitalk.controller.DataTablesResponse;
import org.dk.poitalk.model.EntityClient;
import org.dk.poitalk.model.TipoEntityClient;
import org.dk.poitalk.service.entity.EntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.repackaged.com.google.common.base.StringUtil;
import com.jappstart.model.auth.UserAccount;
import com.jappstart.service.auth.EnhancedUserDetailsService;

/**
 * The admin controller.
 */
@Controller
public class AdminController {
	private static final Logger logger = Logger.getLogger(AdminController.class
			.getName());
    /**
     * The memcache service.
     */
    private MemcacheService memcacheServiceUser;

	private EntityService entityService;

	private LocaleResolver localeResolver;
	
	private EnhancedUserDetailsService userDetailsService;

	private MessageSource messageSource;
	
    /**
     * Returns the memcache service.
     *
     * @return the memcache service
     */
    public final MemcacheService getMemcacheServiceUser() {
        return memcacheServiceUser;
    }

    /**
     * Sets the memcache service.
     *
     * @param memcacheServiceUser the user memcache service
     */
    @Autowired
    public final void setMemcacheServiceUser(
        final MemcacheService memcacheServiceUser) {
        this.memcacheServiceUser = memcacheServiceUser;
    }

	
	public EntityService getEntityService() {
		return entityService;
	}

	@Autowired
	public void setEntityService(EntityService entityService) {
		this.entityService = entityService;
	}

	/**
	 * Gets the locale resolver.
	 * 
	 * @return the locale resolver
	 */
	public final LocaleResolver getLocaleResolver() {
		return localeResolver;
	}

	/**
	 * Sets the locale resolver.
	 * 
	 * @param localeResolver
	 *            the locale resolver
	 */
	@Autowired
	public final void setLocaleResolver(final LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}
	
	/**
	 * Gets the user details service.
	 * 
	 * @return the user details service
	 */
	public final EnhancedUserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	/**
	 * Sets the user details service.
	 * 
	 * @param userDetailsService
	 *            the user details service
	 */
	@Autowired
	public final void setUserDetailsService(
			final EnhancedUserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	

	public MessageSource getMessageSource() {
		return messageSource;
	}
	
	@Autowired
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}


    /**
     * Admin.
     *
     * @return the view name
     */
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public final String create() {
        return "admin";
    }

    /**
     * Flushes memcache.
     *
     * @return the view name
     */
    @RequestMapping(value = "/admin/flush", method = RequestMethod.GET)
    public final String flushCache() {
        memcacheServiceUser.clearAll();
        return "admin";
    }

    private  List<Map<String,Object>> generateDataTable (List<EntityClient> entityClients,HttpServletRequest request){

    	List<Map<String,Object>> listDataTable = new ArrayList<Map<String,Object>>();
    	Map<String,Object> mapDataRows= null;
		
		UserAccount userAccount1 = null;
		
		for (EntityClient entityClient : entityClients) {
			mapDataRows = new HashMap<String, Object>();
			String addressServletFeedbacking = this.messageSource.getMessage("address.servlet.feedbacking", null, getLocaleResolver().resolveLocale(request));
			mapDataRows.put("keyQRCode",addressServletFeedbacking + "?idplace=" + entityClient.getIdPlace() + "&tipoentityclient=" + TipoEntityClient.GOOGLEPLACE);
			mapDataRows.put("idPlace",entityClient.getIdPlace());
			mapDataRows.put("tipoEntityClient",entityClient.getTipoEntityClient());
			userAccount1 = entityClient.getUserAccount();
			mapDataRows.put("username",userAccount1.getUsername());
			logger.info(String.format("resultAdhoc tiene la siguiente pinta %s",mapDataRows));
			listDataTable.add(mapDataRows);
		}
		
		return listDataTable;
    }
    
    /** TODO Cambiar el delete por la Activación*/
    @RequestMapping(value="/admin/searchx", method= RequestMethod.POST)
    public @ResponseBody
    DataTablesResponse<Map<String,Object>> searchx(@RequestBody DataTablesRequest dataTablesRequest, HttpServletRequest request, HttpServletResponse response) {
       
		logger.info(String.format("La dataTablesRequest contiene  %s = ",
				dataTablesRequest.toString()));
		
    	DataTablesResponse<Map<String,Object>> dataTablesResponse = new DataTablesResponse<Map<String,Object>>();

//      List<EntityClient> listDataTable = entityService.search(null);
    	
		//String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
    	String username = dataTablesRequest.searchQuery;
    	if (!StringUtil.isEmptyOrWhitespace(username)){
	    	
			UserAccount userAccount = getUserDetailsService().getUser(username);
			
			if (userAccount != null){
				List<EntityClient> entityClients = userAccount.getEntityClients();
				logger.info(String.format("La searchx devuelve  %d filas",entityClients.size()));	
				
				List<Map<String,Object>> listDataTable = this.generateDataTable(entityClients,request);
				
				
		        if (!listDataTable.isEmpty()) {
		        	dataTablesResponse.echo = dataTablesRequest.echo;
		        	dataTablesResponse.totalRecords = listDataTable.size();
		        	dataTablesResponse.totalDisplayRecords = listDataTable.size();
		        	int endSubList = ((dataTablesRequest.displayStart+dataTablesRequest.displayLength)>listDataTable.size())?listDataTable.size():(dataTablesRequest.displayStart+dataTablesRequest.displayLength);
		        	dataTablesResponse.data = listDataTable.subList(dataTablesRequest.displayStart,endSubList);
		        	dataTablesResponse.columns = "{idPlace,tipoEntityClient,username,qrcode,actions}";
		        }
//		        else {
//		            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);        	      	
//		         }
			}
    	}	
        return dataTablesResponse;
    }
}
